// HTML编码解码

function escape2Html(str) {
    var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}

function html2Escape(sHtml) {
    return sHtml.replace(/[<>&"]/g,function(c){return {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c];});
}

$(function () {
    window.ue = UE.getEditor('container');
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        if (action == 'uploadimage') {
            // return 'http://localhost:8080/gtw/uploadimage';
            return '/liquor/uploadimage';
        }else {
            return this._bkGetActionUrl.call(this, action);
        }
    };
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/membercommodity/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: 'id', width: 50, key: true },
            { label: '商品名称', name: 'commodityname', index: 'commodityName', width: 80 },
            { label: '商品编号', name: 'commoditynum', index: 'commodityNum', width: 80 },
            { label: '分类名称', name: 'categoryname', index: 'categoryName', width: 80 },
            { label: '普通价格', name: 'price', index: 'price', width: 80,formatter:function(value,options,row){
                return value/100;
            }},
            { label: '会员价', name: 'pricediscounts', index: 'priceDiscounts', width: 80,formatter:function(value,options,row){
                return value/100;
            } },
            { label: '销量', name: 'salesnum', index: 'salesNum', width: 80 },
            { label: '邮费', name: 'freight', index: 'freight', width: 80,formatter:function(value,options,row){
                return value/100;
            } },
            { label: '需要支付', name: 'ispay', index: 'isPay', width: 80 ,formatter: function (value, options, row) {
                return value === false ?
                    '<span class="label label-danger">否</span>' :
                    '<span class="label label-success">是</span>';
            }},
            { label: '新品', name: 'isnew', index: 'isNew', width: 80 ,formatter: function (value, options, row) {
                return value === false ?
                    '<span class="label label-danger">否</span>' :
                    '<span class="label label-success">是</span>';
            }},
            { label: '推荐', name: 'isrecommend', index: 'isRecommend', width: 80 ,formatter: function (value, options, row) {
                return value === false ?
                    '<span class="label label-danger">否</span>' :
                    '<span class="label label-success">是</span>';
            }},
            { label: '热门', name: 'ishot', index: 'isHot', width: 80 ,formatter: function (value, options, row) {
                return value === false ?
                    '<span class="label label-danger">否</span>' :
                    '<span class="label label-success">是</span>';
            }},
            { label: '明星商品', name: 'celebrity', index: 'celebrity', width: 80 ,formatter: function (value, options, row) {
                return value === false ?
                    '<span class="label label-danger">否</span>' :
                    '<span class="label label-success">是</span>';
            }},
            { label: '优选商品', name: 'preferred', index: 'preferred', width: 80 ,formatter: function (value, options, row) {
                return value === false ?
                    '<span class="label label-danger">否</span>' :
                    '<span class="label label-success">是</span>';
            }}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});

var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            commodityname : null
        },
        showList: true,
        title: null,
        membercommodity: {
            picurl:"[]"
        },
        sels: []
    },
    created: function () {
        $.ajax({
            url: baseURL + 'sys/category/findAll',
            type: "POST",
            contentType: "application/json",
            success: function (result) {
                vm.sels = result.list
            },
            error: function (error) {
                alert('数据加载失败!');
            }
        })
    },
    methods: {
        removePic:function(index){
            //removePic
            var _pics = JSON.parse(vm.commodity.picurl);
            _pics.splice(index , 1);

            vm.commodity.picurl = JSON.stringify(_pics)
            console.log('Del a pic.' , _pics)
        },
        changeImage: function(e) {
            var file = e.target.files[0]
            var reader = new FileReader()
            var THIS = this
            reader.readAsDataURL(file)
            reader.onload = function(e) {
                // this.result 为图片
                THIS.upload(this.result)
            }
        },
        upload: function(data) {
            // 上传图片
            var THIS = this;
            if(this.$refs.file.files.length !== 0) {
                var image = new FormData()
                image.append('file', this.$refs.file.files[0])

                $.ajax({
                    url: '/liquor/uploadimage3',
                    data: image,
                    // headers: {
                    //     "Content-Type": "multipart/form-data"
                    // },
                    cache: false,
                    processData: false,
                    contentType: false,
                    type: 'post',
                    success: function(result) {

                        var __thisPics = JSON.parse(THIS.membercommodity.picurl);
                        __thisPics.unshift(result.address);

                        THIS.membercommodity.picurl = JSON.stringify(__thisPics)
                    },
                    error: function(error) {
                        alert('图片上传失败!');
                    }
                })
            }
        },
        query: function () {
            vm.reload();
        },
        query2: function(){
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            vm.showList = false;
            vm.title = "查看";
            vm.getInfo(id)
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.commodity = {
                picurl:"[]"
            }
        },
        getPropertyList: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }


            vm.showDom = "propertyList"
            window.location.href = 'membercommodityProperty.html?id='+id
        },
        update: function (event) {
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            var _htmlContent = vm.getUeditor();

            vm.membercommodity.commoditydetails =html2Escape(_htmlContent);

            demo = JSON.stringify(vm.membercommodity);
            console.info(demo)
            var url = vm.commodity.id == null ? "sys/membercommodity/save" : "sys/membercommodity/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.membercommodity),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/membercommodity/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getUeditor: function () {
            var ue = UE.getEditor('container');
            var _html = ue.getContent();
            return _html
        },
        getInfo: function(id){
            $.get(baseURL + "sys/membercommodity/info/"+id, function(r){
                r.membercommodity.commoditydetails = escape2Html(r.membercommodity.commoditydetails )
                window.ue.setContent(r.membercommodity.commoditydetails);
                vm.membercommodity = r.membercommodity;
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'commodityname': vm.q.commodityname},
                page:page
            }).trigger("reloadGrid");
        },
    }
});